package B2;

import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class Str {
    private String str;
    private Integer num=3;
    private boolean inputC(String str){
        Scanner sc=new Scanner(System.in);
        while(true){
            System.out.println("请输入字符串：");
            str=sc.nextLine();
            if(str.length()==4){this.str=str; return true;}
            else{System.out.println("字符串长度不为4，请重新输入！\n");}
        }
    }
    public boolean isRight(String pass) {
        if(inputC(this.str)){
            if(pass.equals(this.str)){System.out.println("密码正确！"); return true;}
            else{num--; System.out.println("密码错误！还剩"+ num +"次机会！");
                if(num==0){
                    System.out.println("密码错误次数已达上限，请等待120秒后重新输入！（这里为5秒）");
                    AtomicReference<Integer> number= new AtomicReference<>(5);
                    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
                    Runnable task = () -> {
                        System.out.println(number.getAndSet(number.get() - 1));
                        if (number.get() == 0) {
                            scheduler.shutdown();
                            num=3;
                            isRight(pass);
                        }
                    };
                    scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
                    return false;
                }
                return isRight(pass);
            }
        }else{return false;}
    }
}